package com.demo.demo.controller;

import com.com.base.bean.ResultMessage;
import com.com.base.util.ResultMessageUtil;
import com.demo.demo.domain.Order;
import com.demo.demo.service.OrderService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RequestMapping("/order")
@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;

    @RequestMapping("/add")
    public ResultMessage add(@RequestBody Order order) {
        if (orderService.add(order) > 0) {
            return ResultMessageUtil.success("添加成功");
        } else {
            return ResultMessageUtil.error("添加失败");
        }
    }

    @RequestMapping("/find_time")
    public ResultMessage findByTime(@RequestParam String begin_time, @RequestParam String end_time) {
        List<Order> list = new ArrayList<>();
        try {
            list = orderService.findByTime(DateUtils.parseDate(begin_time, "yyyy/MM/dd", "yyyy-MM-dd"), DateUtils.parseDate(end_time, "yyyy/MM/dd", "yyyy-MM-dd"));
        } catch (Exception e) {
            return ResultMessageUtil.error("日期格式错误");
        }
        return ResultMessageUtil.success("", list);
    }

    @RequestMapping("/find_timeanduserid")
    public ResultMessage findByTime(@RequestParam long userid, @RequestParam String begin_time, @RequestParam String end_time) {
        List<Order> list = new ArrayList<>();
        try {
            list = orderService.findByTimeAndUserId(DateUtils.parseDate(begin_time, "yyyy/MM/dd", "yyyy-MM-dd"), DateUtils.parseDate(end_time, "yyyy/MM/dd", "yyyy-MM-dd"), userid);
        } catch (Exception e) {
            return ResultMessageUtil.error("日期格式错误");
        }
        return ResultMessageUtil.success("", list);
    }

    @RequestMapping("/del")
    public ResultMessage del(@RequestParam long onlyC) {
        try {
            orderService.delete(onlyC);
        } catch (Exception e) {
            return ResultMessageUtil.error(e.getMessage());
        }

        return ResultMessageUtil.success("");
    }
}
